package com.itheima.service.mongo.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class VideoServiceImpl implements VideoService {
    @Autowired
    private MongoTemplate mongoTemplate;

    //根据用户的id 查询视频的推荐数据
    @Override
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.计算
        int startIndex = (pageNum-1)*pageSize;
        //2.封装query
        Query query = new Query(
                Criteria.where("userId").is(userId) //推荐给谁
        ).with(Sort.by(Sort.Order.desc("date")))//排序
                .skip(startIndex).limit(pageSize);//分页
        //3.查询
        List<RecommendVideo> recommendVideoList = mongoTemplate.find(query, RecommendVideo.class);
        //4.构建counts
        long count = mongoTemplate.count(query, RecommendVideo.class);

        //直接转换成video  好处: 一会在manager 不用再转换了(不用再远程调用了)  为什么不在此处封装userInfo
        //userInfo 是mysql服务器  , 此服务器是专门操作mongo
        List<Video> videoList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(recommendVideoList)){
            for (RecommendVideo recommendVideo : recommendVideoList) {
                ObjectId videoId = recommendVideo.getVideoId(); //视频的id  ObjectId
                Video video = mongoTemplate.findById(videoId, Video.class);//查询视频对象
                videoList.add(video);
            }
        }


        return new PageBeanVo(pageNum , pageSize , count , videoList);
    }

    @Autowired
    private RedisIdService redisIdService;
    //保存视频
    @Override
    public void publishVideo(Video video) {
        //给发布的视频生成一个 数字id 供大数据使用
        Long vid = redisIdService.getNextId(ConstantUtil.VIDEO_ID);
        video.setVid(vid);
        //保存视频
        mongoTemplate.save(video);

        //将视频推送给自己 (根据将来的业务需求)
        RecommendVideo recommendVideo = new RecommendVideo();
        recommendVideo.setDate( System.currentTimeMillis());//时间
        recommendVideo.setVid(vid); // 大数据的id
        recommendVideo.setUserId( video.getUserId() );//推荐给自己
        recommendVideo.setVideoId( video.getId() ); //视频的id
        recommendVideo.setScore(RandomUtil.randomDouble(66,99));//推荐的得分
        mongoTemplate.save(recommendVideo);
    }
}
